<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    width="80%"
    destroy-on-close
    class="friend-select-dialog"
    @close="handleClose"
    :style="{ marginTop: '5vh' }"
  >
    <div class="dialog-content">
      <!-- 搜索和筛选区域 -->
      <div class="filter-section">
        <div class="search-row">
          <el-input v-model="searchKeyword" placeholder="搜索好友名称" clearable class="search-input">
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-select v-model="selectedTags" multiple placeholder="标签筛选" clearable class="search-input">
            <el-option v-for="tag in tagList" :key="tag.id" :label="tag.label_name" :value="tag.id" />
          </el-select>
          <div class="button-group">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </div>
        </div>
      </div>

      <!-- 好友列表 -->
      <div class="card-section" v-loading="loading">
        <div class="friend-cards-grid">
          <div
            v-for="friend in friendList"
            :key="friend.wxAccount"
            class="friend-card"
            :class="{ selected: isSelected(friend) }"
            @click="handleCardClick(friend)"
          >
            <!-- 多选模式下的选择框 -->
            <div v-if="multiple" class="card-checkbox">
              <el-checkbox :model-value="isSelected(friend)" @change="(val) => handleCheckboxChange(friend, val)" @click.stop />
            </div>

            <!-- 好友头像 -->
            <div class="card-avatar">
              <el-avatar :size="50" :src="friend.avatarUrl" :alt="friend.userName">
                <el-icon><User /></el-icon>
              </el-avatar>
            </div>

            <!-- 好友信息 -->
            <div class="card-content">
              <div class="friend-name" :title="friend.userName">
                {{ friend.userName }}
              </div>
              <div v-if="friend.remark" class="friend-remark" :title="friend.remark">
                {{ friend.remark }}
              </div>

              <!-- 标签 -->
              <div v-if="friend.labels && friend.labels.length > 0" class="friend-tags">
                <el-tag v-for="tag in friend.labels.slice(0, 3)" :key="tag.id" size="small" class="friend-tag">
                  {{ tag.label_name }}
                </el-tag>
                <el-tooltip
                  v-if="friend.labels.length > 3"
                  :content="
                    friend.labels
                      .slice(3)
                      .map((tag) => tag.label_name)
                      .join('、')
                  "
                  placement="top"
                >
                  <el-tag size="small" class="friend-tag more-tag"> +{{ friend.labels.length - 3 }} </el-tag>
                </el-tooltip>
              </div>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="!loading && friendList.length === 0" class="empty-state">
          <el-empty description="暂无好友数据" />
        </div>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 15, 20, 25, 30]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts">
import { defineComponent } from 'vue';

export default defineComponent({
  name: 'FriendSelectDialog'
});
</script>

<script lang="ts" setup>
import { ref, computed, watch, onMounted } from 'vue';
import { Search, User } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { contactsPage } from '@/api/wechat';
import { getAllLabel } from '@/api/userRate/label';
import AiWechatInfo from '@/components/AiWechatInfo/index.vue';

interface Tag {
  id: string;
  label_name: string;
}

interface Friend {
  wx_id: string;
  customer_id: string;
  userName: string;
  wxAccount: string;
  avatarUrl: string;
  labels: Tag[];
  labelName?: string;
  createTime: string;
  updateTime: string;
  user_id: string;
  userQq?: string;
  userCustomerSource?: string;
  userDescription?: string;
  userAge?: string;
  gender: number;
  userAddress?: string;
  userAssignedEmployee?: string;
  userBirthday?: string;
}

interface MsgContactsParams {
  wxId: string;
  current: number;
  size: number;
  userName?: string;
  ids?: string;
}

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  multiple: {
    type: Boolean,
    default: false
  },
  title: {
    type: String,
    default: '选择好友'
  },
  tagList: {
    type: Array as () => Tag[],
    default: () => []
  },
  selectedFriends: {
    type: Array as () => string[],
    default: () => []
  }
});

const emit = defineEmits(['update:modelValue', 'confirm', 'cancel']);

// 状态变量
const loading = ref(false);
const searchKeyword = ref('');
const selectedTags = ref<string[]>([]);
const currentPage = ref(1);
const pageSize = ref(15);
const total = ref(0);
const friendList = ref<Friend[]>([]);
const wxId = ref(JSON.parse(localStorage.getItem('msgprofile') || '{}').wx_id);
const tempSelectedFriends = ref<Friend[]>([]);
const tagList = ref<Tag[]>([]);

// 计算属性
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
});

// 方法
const fetchFriends = async () => {
  loading.value = true;
  try {
    const params: MsgContactsParams = {
      wxId: wxId.value,
      current: currentPage.value,
      size: pageSize.value,
      userName: searchKeyword.value,
      ids: selectedTags.value.length > 0 ? selectedTags.value.join(',') : undefined
    };
    const res = await contactsPage(params);
    friendList.value = res.data.records || [];
    total.value = res.data.total || 0;

    // 初始化临时选中数据
    if (props.selectedFriends.length > 0) {
      tempSelectedFriends.value = friendList.value.filter((f) => props.selectedFriends.includes(f.wxAccount));
    }
  } catch (error) {
    ElMessage.error('获取好友列表失败');
  } finally {
    loading.value = false;
  }
};

const handleReset = () => {
  searchKeyword.value = '';
  selectedTags.value = [];
  currentPage.value = 1;
  pageSize.value = 15;
  fetchFriends();
};

const handleSearch = () => {
  currentPage.value = 1;
  fetchFriends();
};

const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1;
  fetchFriends();
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  fetchFriends();
};

const isSelected = (friend: Friend) => {
  return tempSelectedFriends.value.some((f) => f.wxAccount === friend.wxAccount);
};

const handleCancel = () => {
  emit('cancel');
  dialogVisible.value = false;
};

const handleConfirm = () => {
  const selectedFriends = tempSelectedFriends.value.map((f) => ({
    id: f.wxAccount,
    wx_id: f.wxAccount,
    wxAccount: f.wxAccount,
    nick_name: f.userName,
    first_nick_name: f.userName,
    avatar: f.avatarUrl,
    avatarUrl: f.avatarUrl,
    userName: f.userName
  }));
  emit('confirm', selectedFriends);
  dialogVisible.value = false;
};

const handleClose = () => {
  searchKeyword.value = '';
  selectedTags.value = [];
  currentPage.value = 1;
};

// 卡片相关方法
const handleCardClick = (friend: Friend) => {
  if (props.multiple) {
    // 多选模式：切换选中状态
    const index = tempSelectedFriends.value.findIndex((f) => f.wxAccount === friend.wxAccount);
    if (index > -1) {
      tempSelectedFriends.value.splice(index, 1);
    } else {
      tempSelectedFriends.value.push(friend);
    }
  } else {
    // 单选模式：直接设置选中
    tempSelectedFriends.value = [friend];
  }
};

const handleCheckboxChange = (friend: Friend, checked: boolean) => {
  if (checked) {
    if (!tempSelectedFriends.value.some((f) => f.wxAccount === friend.wxAccount)) {
      tempSelectedFriends.value.push(friend);
    }
  } else {
    const index = tempSelectedFriends.value.findIndex((f) => f.wxAccount === friend.wxAccount);
    if (index > -1) {
      tempSelectedFriends.value.splice(index, 1);
    }
  }
};

// 获取标签列表
const fetchTagList = async () => {
  try {
    const res = await getAllLabel();
    if (res.data) {
      tagList.value = res.data;
    }
  } catch (error) {
    ElMessage.error('获取标签列表失败');
  }
};

onMounted(() => {
  fetchTagList();
});

// 监听弹窗显示状态
watch(
  () => props.modelValue,
  (val) => {
    if (val) {
      fetchFriends();
    }
  }
);
</script>

<style lang="scss" scoped>
.friend-select-dialog {
  :deep(.el-dialog) {
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 4px 24px rgba(0, 0, 0, 0.08);
    .el-dialog__header {
      margin: 0;
      padding: 20px 24px;
      border-bottom: 1px solid #f0f0f0;

      .el-dialog__title {
        font-size: 18px;
        font-weight: 600;
        color: #1f2937;
      }
    }

    .el-dialog__body {
      padding: 24px;
    }

    .el-dialog__footer {
      padding: 16px 24px;
      border-top: 1px solid #f0f0f0;
    }
  }
}

.dialog-content {
  .filter-section {
    margin-bottom: 16px;
    background: #f9fafb;
    padding: 12px;
    border-radius: 8px;

    .search-row {
      display: flex;
      gap: 12px;
      align-items: center;

      .search-input {
        flex: 1;
        min-width: 0;

        :deep(.el-input__wrapper) {
          box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
          background: #fff;

          &:hover,
          &:focus-within {
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
          }
        }
      }

      .button-group {
        display: flex;
        flex-shrink: 0;
      }
    }
  }

  .card-section {
    background: #fff;
    min-height: 400px;

    .friend-cards-grid {
      display: grid;
      grid-template-columns: repeat(5, 1fr);
      gap: 8px;
      padding: 8px;

      @media (max-width: 1400px) {
        grid-template-columns: repeat(4, 1fr);
      }

      @media (max-width: 1200px) {
        grid-template-columns: repeat(3, 1fr);
      }

      @media (max-width: 768px) {
        grid-template-columns: repeat(2, 1fr);
      }

      @media (max-width: 480px) {
        grid-template-columns: 1fr;
      }
    }

    .friend-card {
      position: relative;
      background: #fff;
      border: 1px solid #e5e7eb;
      border-radius: 8px;
      padding: 10px;
      cursor: pointer;
      transition: all 0.3s ease;
      display: flex;
      flex-direction: column;
      align-items: center;
      text-align: center;
      min-height: 140px;

      &:hover {
        border-color: #3b82f6;
        box-shadow: 0 4px 12px rgba(59, 130, 246, 0.15);
        transform: translateY(-2px);
      }

      &.selected {
        border-color: #3b82f6;
        background: #eff6ff;
        box-shadow: 0 4px 12px rgba(59, 130, 246, 0.2);
      }

      .card-checkbox {
        position: absolute;
        top: 8px;
        right: 8px;
        z-index: 2;
      }

      .card-avatar {
        margin-bottom: 6px;

        :deep(.el-avatar) {
          border: 2px solid #f3f4f6;
          transition: border-color 0.3s ease;
        }
      }

      &.selected .card-avatar :deep(.el-avatar) {
        border-color: #3b82f6;
      }

      .card-content {
        flex: 1;
        width: 100%;
        display: flex;
        flex-direction: column;
        gap: 4px;

        .friend-name {
          font-size: 14px;
          font-weight: 600;
          color: #1f2937;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          width: 100%;
        }

        .friend-remark {
          font-size: 12px;
          color: #6b7280;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          width: 100%;
        }

        .friend-tags {
          display: flex;
          flex-wrap: wrap;
          gap: 2px;
          justify-content: center;
          margin-top: 4px;
          max-height: 40px;
          overflow: hidden;

          .friend-tag {
            font-size: 10px;
            padding: 1px 4px;
            border-radius: 8px;
            background: #f3f4f6;
            border-color: #e5e7eb;
            color: #4b5563;
            border: 1px solid #e5e7eb;
            line-height: 1.2;

            &.more-tag {
              background: #e5e7eb;
              color: #6b7280;
              cursor: pointer;

              &:hover {
                background: #d1d5db;
              }
            }
          }
        }
      }
    }

    .empty-state {
      padding: 60px 20px;
      text-align: center;
    }
  }

  .pagination-container {
    padding: 12px;
    display: flex;
    justify-content: flex-end;
    background: #fff;
  }
}

:deep(.dialog-footer) {
  .el-button {
    padding: 8px 20px;
    font-weight: 500;
    border-radius: 6px;

    &--default {
      border-color: #e5e7eb;
      color: #4b5563;

      &:hover {
        border-color: #3b82f6;
        color: #3b82f6;
      }
    }

    &--primary {
      background: #3b82f6;
      border-color: #3b82f6;

      &:hover {
        background: #2563eb;
        border-color: #2563eb;
      }
    }
  }
}
</style>
